package com.wwz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wwz.config.RedisLuaTemplate;
import com.wwz.feign.ProductFeign;
import com.wwz.tcc.TccOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class TaskSchedual {
   private static final Logger logger = LoggerFactory.getLogger(TaskSchedual.class);
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private TccOrderService tccOrderService;
    @Autowired
    private RedisLuaTemplate redisLuaTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    /*@Scheduled(cron = "0/5 * * * * ?")
    @GlobalTransactional*/
    public void postProcess() throws Exception {
            logger.info("===========开始执行定时任务===============");

            List<String> result = redisLuaTemplate.select("DB_QUEUE",20);
            if(!ObjectUtils.isEmpty(result)){
                List<JSONObject> list = new ArrayList<>();
                result.forEach(item->{
                    list.add(JSON.parseObject(StringEscapeUtils.unescapeJavaScript(item)));
                });
                if(tccOrderService.batchInsert(null,JSONObject.toJSONString(list),System.currentTimeMillis())>0){
                    int i = (int)productFeign.update("5","5");
                    if(i<=0){
                        throw new Exception("error");
                    }
                 /*   redisLuaTemplate.increment("DB_QUEUECOPY",JSONObject.toJSONString(result),"io",-1,"100000");*/
                    if(!redisLuaTemplate.removeKey("DB_QUEUE",result.size(),-1)){
                        throw new Exception("");
                    }
                   // productFeign.update()
                }
            }

            logger.info("result：{}",result);
        /*int j =  (int)productFeign.update("5","1");
        int i =  tccOrderService.insert(null,"44",System.currentTimeMillis());*/
            logger.info("===========结束执行定时任务===============");



    }
}
